package com.godyao.mall.goods.service.impl;


import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.godyao.mall.core.model.EsSearchParam;
import com.godyao.mall.core.model.goods.Goods;
import com.godyao.mall.goods.es.model.GoodsEs;
import com.godyao.mall.goods.es.repository.GoodsEsRepository;
import com.godyao.mall.goods.mq.config.RabbitMqConfig;
import com.godyao.mall.goods.mq.model.GoodsMq;
import com.godyao.mall.goods.repository.GoodsRepository;
import com.godyao.mall.goods.service.IGoodsService;
import com.godyao.mall.rabbitmq.service.ISendMsgService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author godyao
 * @date 2022/3/31
 */
@Service
@RequiredArgsConstructor
public class GoodsServiceImpl implements IGoodsService {
    private final GoodsRepository goodsRepository;

    private final GoodsEsRepository goodsEsRepository;

    private final ISendMsgService sendMsgService;


    @Override
    @SneakyThrows
    public Goods save(Goods goods) {
        // 发送消息到MQ，再落到es
        final GoodsMq goodsMq = new GoodsMq();
        // 新增 or 修改
        Integer flag = goods.getId() == null ? 1 : 2;
        final Goods save = goodsRepository.save(goods);
        BeanUtils.copyProperties(goods, goodsMq);
        goodsMq.setFlag(flag);
        sendMsgService.sendMsg(RabbitMqConfig.EXCHANGE_NAME, RabbitMqConfig.ROUTING_KEY, new ObjectMapper().writeValueAsString(goodsMq), null);
        return save;
    }

    @Override
    @SneakyThrows
    public void delGoods(Long goodsId) {
        goodsRepository.deleteById(goodsId);
        GoodsMq goodsMq = new GoodsMq();
        goodsMq.setId(goodsId);
        goodsMq.setFlag(3);
        sendMsgService.sendMsg(RabbitMqConfig.EXCHANGE_NAME,RabbitMqConfig.ROUTING_KEY, new ObjectMapper().writeValueAsString(goodsMq), null);
    }

    @Override
    public Goods findGoodsByGoodsId(Long goodsId) {
        return goodsRepository.findGoodsById(goodsId);
    }

    @Override
    public Page<GoodsEs> search(EsSearchParam param) {
        //去除空格
        //String whiteKeyword = StrUtil.trim(param.getKeyword());
        final PageRequest pageable = PageRequest.of(param.getPageNumber() - 1, param.getPageSize());
        String keyword= StrUtil.replace(param.getKeyword()," ","");
        final List<SearchHit<GoodsEs>> goodsDetailLikeOrGoodsNameLikeOrGoodsTitleLike =
                goodsEsRepository.findByGoodsDetailLikeOrGoodsNameLikeOrGoodsTitleLike(keyword, keyword, keyword, pageable);
        final int totals = goodsEsRepository.countByGoodsDetailLikeOrGoodsNameLikeOrGoodsTitleLike(keyword, keyword, keyword);
        final List<GoodsEs> dataList = new ArrayList<>();
        goodsDetailLikeOrGoodsNameLikeOrGoodsTitleLike.forEach(goodsEsSearchHit -> {
            final GoodsEs content = goodsEsSearchHit.getContent();
            final Map<String, List<String>> highlightFields = goodsEsSearchHit.getHighlightFields();
            for (String s : highlightFields.keySet()) {
                if ("goodsDetail".equals(s)) {
                    content.setGoodsDetail(highlightFields.get(s).get(0));
                }
                if ("goodsTitle".equals(s)) {
                    content.setGoodsTitle(highlightFields.get(s).get(0));
                }
                if ("goodsName".equals(s)) {
                    content.setGoodsName(highlightFields.get(s).get(0));
                }
            }
            dataList.add(content);
        });
        return new PageImpl(dataList, pageable, totals);
    }


    @Override
    public Page<Goods> findPagedGoods(Specification spec, Pageable pageable) {
        return goodsRepository.findAll(spec, pageable);
    }


}
